<template>
	<view class="flex flex-direction" :class="[content == 0 ? 'content' : 'content1']">
		<z-navbar top="calc(44rpx + var(--status-bar-height))"
			:imgUrl="content === 0 ? '/static/image/logo/logo_white.png' : '/static/image/logo/logo.png'">
		</z-navbar>
		<view v-if="content == 0" class="bg-image">
			<image lazy-load src="https://gitee.com/sunway_group_1398400350/lzy_frontend.git"
				mode="aspectFill">
			</image>
		</view>
		<amap v-if="content != 0" :latitude="userSite.latitude" :longitude="userSite.longitude"></amap>
		<!-- <view class="flex-grow"></view> -->
		<view class="po_fiexd">
			<image class="arc" src="/static/image/common/arc.png" mode=""></image>
			<view v-if="content == 2" @tap="jumpPreviousPage" class="flex align-center get-back">
				<image class="width_32 height_32" src="/static/image/icon/arrow_l.png" mode=""></image>
				<text class="fontS24 color_fff margin_l_r15">返回上一页</text>
			</view>
			<view class="line-absolute flex justify-center">
				<view class="line"></view>
			</view>
			<view class="hot-city padding_l_r30" :style="{height: content === 2 ? scrollHeight : ''}">
				<u-loadmore v-if="status === 'loading' && content == 2" iconColor="#FFFFFF" color="#FFFFFF"
					:status="status" loadingText="小荔正在为你生成计划,请稍后~" />
				<template>
					<!-- 	<template v-if="content === 0">
						<view class="flex align-center">
							<u-icon name="arrow-down" color="#FAE9E1" size="19"></u-icon>
							<text class="fontS28 mar_left10">热门城市</text>
						</view>
						<view class="flex flex-wrap align-center gap mar_top20 mar_bottom40">
							<view @click="togglePicker(item,1)"
								class="cities-list fontS28 flex justify-center align-center"
								v-for="(item,index) in state.list" :key="index">
								{{item.name}}
							</view>
						</view>
					</template> -->
					<template v-if="content === 0">
						<view class="flex align-center">
							<image class="width_32 height_32" src="/static/image/icon/lng_mark.png" mode=""></image>
							<text class="fontS26 mar_left10">当前开放城市：成都</text>
						</view>
						<view class="mar_bottom20 mar_top40">
							<scroll-view scroll-y style="height: 300rpx;">
								<view class="plan-list mar_bottom20 flex justify-between align-center"
									v-for="(item,index) in state.dataList" :key="index" @click="togglePicker(item)">
									<view class="fontS28 color_fff">{{item}}</view>
									<image class="width_40 height_40" src="/static/image/icon/frame.png" mode="">
									</image>
								</view>
							</scroll-view>
						</view>
					</template>
					<template v-if="content === 2">
						<view class="flex align-center mar_bottom20">
							<image class="width_32 height_32" src="/static/image/icon/lng_mark.png" mode=""></image>
							<text class="fontS26 mar_left10">成都</text>
						</view>
						<view class="scroll" :style="{height: scrollHeight}">
							<chat :chatList="state.chatList" :scrollHeight="scrollHeight" :scrollViewId="scrollViewId">
							</chat>
						</view>
					</template>
				</template>
				<view class="mar_bottom30" :style="{paddingBottom: keyboardHeight}">
					<z-dialog @onIssue="onIssue" :chatList="state.chatList" placeholder="输入偏好/需求，生成AI旅行计划"
						:textareaVal="textareaVal" @inputFocus="inputFocus" @inputBlur="inputBlur"
						@onTextarea="onTextarea" @send="send">
					</z-dialog>
				</view>
			</view>
			<view class="" style="background-color: rgba(0, 0, 0, 0.6)">
				<z-tabbar :current="1" inactiveColor="rgba(255,255,255,0.6)" :fixed="false"
					@onReLaunch="onReLaunch"></z-tabbar>
			</view>
		</view>

		<u-modal :show="modalShow" :title="title" closeOnClickOverlay @close="modalShow = false" :content="message"
			:cancelText="cancelText" :confirmText="confirmText" showCancelButton @cancel="modalCancel"
			@confirm="modalConfirm" confirmColor="#E5725F">
			<text class="fontS28 color_6D6D6D">{{message}}</text>
			<view @tap="modalShow = false" class="modal-close">
				<image src="/static/image/icon/close.png" mode=""></image>
			</view>
			</u-modal>
	</view>
</template>

<script setup>
	import zNavbar from '@/components/z-navbar/z-navbar.vue';
	import zTabbar from '@/components/z-tabbar/z-tabbar.vue';
	import zDialog from '@/components/z-dialog/z-dialog.vue';
	import chat from '@/components/chat/chat.vue';
	import amap from '@/components/amap/amap.vue';
	import WS from '@/utils/websocket.js';
	import {
		ref,
		reactive,
		computed,
		getCurrentInstance
	} from 'vue';

	import {
		onLoad,
		onShow,
		onUnload,
		onHide,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app';

	import {
		getLocation
	} from "@/utils/common.js";

	import {
		useStore
	} from 'vuex';
	const store = useStore();

	const {
		proxy
	} = getCurrentInstance()

	// 分享到好友
	onShareAppMessage(async (res) => {
		if (res.from === 'button') { // 来自页面内分享按钮
			console.log(res.target)
		}
		return {
			title: '荔知游',
			path: '/pages/dialogue/dialogue'
		}
	})

	// 分享朋友圈
	onShareTimeline(async (res) => {
		if (res.from === 'button') { // 来自页面内分享按钮
		}
		return {
			title: '荔知游',
			path: '/pages/dialogue/dialogue'
		}
	})

	const textareaVal = reactive({
		content: ''
	})

	const isShow = reactive(false);
	const state = reactive({
		list: [],
		dataList: [],
		chatList: [],
	})
	// 加载中状态
	const status = ref('nomore')

	// 设置scroll的高度
	const scrollHeight = ref('auto')
	const setScrollHeight = (descHeight = 0) => {
		uni.getSystemInfo({
			success: (res) => {
				// scrollHeight.value = `calc(${res.screenHeight}px - 700rpx - ${descHeight}px)`
				scrollHeight.value = `calc(${res.screenHeight}px - 600rpx)`
			}
		})
	}

	// 前往发布计划
	const onIssue = (el, type) => {
		if (ws) {
			ws.close();
		}
		proxy.$api.plansSave({
			city: '成都市',
			content: el.chatInfo,
			poiInfo: el.pois,
			privateView: false,
			status: 0,
			title: '',
		}).then(res => {
			if (res.code === "10000") {
				// uni.navigateTo({
				// 	url: `/tourism-schedule-pages/tourism-schedule/tourism-schedule?planUuid=${res.data.planUuid}`
				// })
				if (type == 'draft') {
					uni.navigateTo({
						url: '/pages/my/my'
					})
				} else {
					uni.navigateTo({
						url: `/pages/loading/loading?planUuid=${res.data.planUuid}`
					})
				}


				// 点击生成清空聊天
				store.commit('changeContent', 0);
				store.commit('changeChatList', []);

				content.value = store.state.content;
				state.chatList = store.state.chatList;
			}
		})
	}

	// 初始化滚动
	const scrollViewId = ref('bottom')
	const initScrollBar = () => {
		setTimeout(() => {
			scrollViewId.value = ''
			setTimeout(() => {
				scrollViewId.value = 'bottom'
				setTimeout(() => {
					scrollViewId.value = ''
				}, 100)
			}, 100)
		}, 100)
	}

	// 步骤
	const content = ref(0)
	const togglePicker = (item, index) => {
		if (uni.getStorageSync('token')) {
			send(item);
			initScrollBar()
		} else {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		}
	}

	// 获取对话推荐词条
	const getChatRecommend = () => {
		proxy.$api.chatRecommend().then(res => {
			if (res.code === "10000") {
				state.dataList = res.data
			}
		})
	}
	// 监听输入聚焦
	const keyboardHeight = ref('auto');
	const inputFocus = (e) => {
		// setKeyboardHeight(e.detail.height);
		if (content.value === 0) {
			setKeyboardHeight(e.detail.height > 0 ? 64 : '');
		} else if (content.value === 2) {
			setKeyboardHeight(e.detail.height > 0 ? e.detail.height : '');
		}
	}
	// 监听输入框失去焦点
	const inputBlur = () => {
		setKeyboardHeight('auto');
	}
	// 监听键盘高度
	const setKeyboardHeight = (descHeight = 0) => {
		// #ifdef MP-WEIXIN
		keyboardHeight.value = `calc(${descHeight}rpx)`;
		// #endif
	}

	// 子组件响应输入框内容
	const onTextarea = (e) => {
		textareaVal.content = e
	}
	// 消息发送触发聊天
	let ws = null
	const send = (e) => {
		// 发送清空输入框
		textareaVal.content = '';
		if (!uni.getStorageSync('isSuccess')) {
			// 加载中动画
			status.value = 'loading'

			content.value = 2;
			store.commit('changeContent', 2);
			// push自己的消息
			state.chatList.push({
				chatInfo: e,
				msgType: "text",
				source: 1
			})
			// 创建连接参数
			const params = {
				token: uni.getStorageSync('token'),
				chatid: '',
				time: new Date().getTime(),
				message: e
			}

			ws = new WS({
				// 连接websocket所需参数
				data: params,
				// 首次连接成功之后，断线重新连接后也会触发（防止断线期间对方发送消息未接收到）
				onConnected: () => {
					ws.sendSocketMessage(params.message);
					// toDo
					// 一般用于请求历史消息列表 getHistoryList()
				},
				// 监听接收到服务器消息
				onMessage: (data) => {
					// toDo
					// 一般用于将最新的一条消息展示在页面上
					status.value = 'nomore';
					console.log(status.value, 999)
					const pois = JSON.parse(data.pois);
					if (pois.poi_data) {
						Object.keys(pois.poi_data).forEach(item => {
							const reg = '**' + item + '**';
							const n =
								`<span style='color: #E5725F;font-weight: bold;'>${item}</span>`;
							data.chatInfo = data.chatInfo.replace(reg, n);

						})
					}
					state.chatList.push({
						...data,
						chatInfo: data.chatInfo,
						msgType: "text",
						source: 2
					})

					store.commit('changeChatList', state.chatList);

					initScrollBar();
				}
			})
		} else {
			const params = {
				message: e
			}
			ws.sendSocketMessage(params);
			state.chatList.push({
				chatInfo: e,
				msgType: "text",
				source: 1
			})

			store.commit('changeChatList', state.chatList);

			initScrollBar();
		}
	}

	// 返回聊天
	const stas = ref(false); // 判断ai是否返回内容 ---- 出现对应弹框
	const modalShow = ref(false);
	const title = ref('确定离开当前页面？');
	const message = ref('');
	const cancelText = ref('取消');
	const confirmText = ref('确定');
	const switchTab = ref(''); // 是否跳转
	const jumpPreviousPage = () => {
		if (state.chatList.length > 0) {
			const obj = state.chatList[state.chatList.length - 1];
			if (obj.source == 1) {
				stas.value = true;
			} else {
				stas.value = false;
			}
		}
		if (stas.value) {
			modalShow.value = true;
		} else {
			message.value = '对话内容可以存为草稿，可在我的中查看';
			cancelText.value = '离开当前页面';
			confirmText.value = '保存为草稿';
			modalShow.value = true;
		}
	}
	// 用户点击了取消
	const modalCancel = () => {
		if (stas.value) {
			modalShow.value = false;
		} else {
			if (ws) {
				ws.close();
			}
			if (switchTab.value) {
				uni.reLaunch({
					url: switchTab.value
				})
			}
			// 点击生成清空聊天
			store.commit('changeContent', 0);
			store.commit('changeChatList', []);
			content.value = store.state.content;
			state.chatList = store.state.chatList;

			modalShow.value = false;
		}
	}
	// 用户点击了确定
	const modalConfirm = () => {
		if (stas.value) {
			if (ws) {
				ws.close();
			}
			if (switchTab.value) {
				uni.reLaunch({
					url: switchTab.value
				})
			}
			// 点击生成清空聊天
			store.commit('changeContent', 0);
			store.commit('changeChatList', []);
			content.value = store.state.content;
			state.chatList = store.state.chatList;

			modalShow.value = false;
		} else {
			let tsList = []
			state.chatList.forEach(item => {
				if (item.source == 2 && item.type != -1) {
					tsList.push(item)
				}
			})
			const content = tsList[tsList.length - 1];
			onIssue(content, 'draft');

			modalShow.value = false;
		}
	}

	// 切换tabbar 
	const onReLaunch = (el) => {
		switchTab.value = el;
		if (content.value === 2) {
			jumpPreviousPage();
		} else {
			uni.reLaunch({
				url: el
			})
		}
	}

	// 页面销毁，断开websocket
	onHide(() => {
		if (ws) {
			ws.close();
		}
	})
	onShow(() => {
		getChatRecommend();
		setScrollHeight();
		if (!ws) {
			uni.removeStorageSync('isSuccess');
		}
	})
	// 获取当前用户经纬度
	const userSite = ref({})
	onLoad((options) => {
		// 获取高度
		setScrollHeight();
		// vuex存储赋值
		content.value = store.state.content;
		state.chatList = store.state.chatList;
		if (state.chatList.length > 0) {
			const obj = state.chatList[state.chatList.length - 1];
			if (obj.source == 1) {
				// 加载中动画
				status.value = 'loading'
			} else {
				// 隐藏加载中动画
				status.value = 'nomore'
			}
		}
		// getLocation();
		// 获取用户当前地址
		if (uni.getStorageSync('user_site')) {
			userSite.value = JSON.parse(uni.getStorageSync('user_site'))
		}
	})
</script>

<style lang="scss" scoped>
	:deep(.u-tabbar__content) {
		background: transparent !important;
		backdrop-filter: blur(4rpx) !important;
	}

	.content {
		width: 750rpx;
		overflow-x: auto;
		background: url('http://139.155.156.160/group1/M00/00/00/i5ucoGUhI3yAc_FjAARtN4H20Sk876.png') no-repeat;
		background-size: 100% 100%;
		height: 100vh;
		overflow-y: auto;
		z-index: -2;
	}

	.content1 {
		width: 750rpx;
		overflow-x: auto;
		background: transparent;
		height: 100vh;
		overflow-y: auto;
		z-index: -2;
	}

	.bg-image {
		width: 100%;
		overflow: hidden;
		height: 600rpx;
		position: absolute;
		top: 29%;
		left: 50%;
		z-index: 0;
		transform: translate(-50%, -50%);
		text-align: center;

		image {
			position: absolute;
			left: 45%;
			transform: translate(-50%);
			width: 1200rpx;
			height: inherit;
			overflow: hidden;
		}
	}

	.arc {
		width: 100%;
		height: 162rpx;
		display: flex;
	}

	.get-back {
		position: absolute;
		top: 110rpx;
		left: 118rpx;
		transform: translate(-50%, -50%);
	}

	.po_fiexd {
		position: fixed;
		bottom: 0;
		width: 100%;
		backdrop-filter: blur(4rpx);

		.line-absolute {
			position: absolute;
			top: 0;
			left: 50%;
			transform: translate(-50%);
		}

		.line {
			background: #fff;
			border-radius: 4rpx;
			margin-top: 30rpx;
			width: 160rpx;
			height: 8rpx;
		}

		.hot-city {
			background-color: rgba(0, 0, 0, 0.6);
			overflow: hidden;
			display: flex;
			flex-direction: column;

			text {
				color: #fff;
			}

			.gap {
				overflow: hidden;
				gap: 30rpx;

				.cities-list {
					width: 150rpx;
					height: 50rpx;
					border-radius: 40rpx;
					background: #FAE9E1;
				}
			}

			.plan-list {
				gap: 30rpx;
			}
		}
	}

	.scroll {
		padding-bottom: 30rpx;
		overflow-y: auto;
		transition: all 0.1s ease;
		flex-grow: 1;
	}

	:deep(.u-textarea) {
		min-height: 45rpx !important;
		padding: 23rpx 80rpx 18rpx 28rpx !important;
		border-radius: 40rpx !important;
		color: #000 !important;
		font-size: 30rpx !important;
		align-items: center !important;
	}

	:deep(.u-textarea__field) {
		color: #000 !important;
		font-size: 28rpx !important;
	}
	
	.modal-close {
		width: 30rpx;
		height: 30rpx;
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		
		image {
			width: 30rpx;
			height: 30rpx;
		}
	}
</style>